<?php


namespace App\Service;


use App\Model\MjSignLog;
use Hyperf\DbConnection\Db;

class PlayService
{
    const ADD_SCORE = [
        0 => 30,
        1 => 5,
        2 => 10,
        3 => 15,
        4 => 20,
        5 => 25,
        6 => 30,
    ];

    /**
     * 得到已经签到的累计签到
     *
     * @return
     */
    public static function index($uid)
    {
        $logInfo = MjSignLog::getSignLogByUid($uid);
        if ($logInfo) { //数据库有签到记录的
            $data = $logInfo->sign_period_data;
            if (!empty($data)) {
                foreach ($data as $k => $v) {
                    $data[$k] = (int)$v;
                }
            }
            return $data;
        } else {
            $key = 'game_play_sign_type_' . $uid;
            return redis()->sMembers($key);
        }
    }

    public static function sign($uid, &$msg)
    {
        $historyData = []; //历史签到记录
        $logInfo = MjSignLog::getSignLogByUid($uid);
        if (!$logInfo) { //数据库没有签到记录的
            //查询redis中是否存在缓存的历史签到数据
            $historyData['sign_data'] = self::signList($uid);
            $redis = redis();
            $key = 'game_play_sign_type_' . $uid;
            $historyData['sign_period_data'] = $redis->sMembers($key);
        }
        $week = date('w');
        $dateTime = date('Y-m-d');
        $historyData['sign_data'] = self::signList($uid);
        if ((!empty($historyData) && isset($historyData['sign_data'][$dateTime])) || isset($logInfo->sign_data[$dateTime])) {
            $msg = '已经签到了';
            return false;
        }
        Db::beginTransaction();
        try {
            //添加签到记录
            MjSignLog::addSignLog($uid, $week, $dateTime, $historyData);
            //更新积分流水
            self::update_user_score('+', self::ADD_SCORE[$week], $uid, '麻将游戏签到');
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollback();
            $msg = '签到失败，请联系客服';
            return false;
        }
    }

    /**
     * 新阶段性提现
     * @param $type
     * @param $uid
     * @param $msg
     */
    public static function sign_by_type($type, $uid, &$msg)
    {
        $config = [3 => 10, 5 => 20, 7 => 30];
        $logInfo = MjSignLog::getSignLogByUid($uid);
        if ($logInfo) { //数据库有签到记录的
            if ($logInfo->num < $type) {
                $msg = '签到天数不足';
                return false;
            }
            if (in_array($type, $logInfo->sign_period_data)) {
                $msg = '已经签到过了';
                return false;
            }
            Db::beginTransaction();
            try {
                MjSignLog::addSignPeriodLog($uid, $type);
                self::update_user_score('+', $config[$type], $uid, '麻将游戏累计签到');
                DB::commit();
                return true;
            } catch (\Exception $e) {
                DB::rollback();
                $msg = '签到失败，请联系客服';
                return false;
            }
        }
        //老流程做保留，数据都入库后可抛弃
        $key = 'game_play_sign_type_' . $uid;

        $redis = redis();


        $relation_key = 'game_play_relation_sign_' . $uid;

        if ($redis->get($relation_key) < $type) {
            $msg = '签到天数不足';
            return false;
        }

        if ($redis->sIsMember($key, $type)) {
            $msg = '已经签到过了';
            return false;
        }

        $redis->sAddArray($key, [$type]);

        self::update_user_score('+', $config[$type], $uid, '麻将游戏');

        $date = new \DateTime();//时间对象

        $date->modify("this week +6 days");//该周的最后一天

        $end_time = $date->format('Y-m-d') . ' 23:59:59';

        //得到本周最后一天的时间戳
        $expire = strtotime($end_time) - time();

        $redis->expire($key, $expire);

        return true;
    }

    public static function signList($uid)
    {
        $logInfo = MjSignLog::getSignLogByUid($uid);
        if ($logInfo) { //数据库有签到记录的
            return $logInfo->sign_data;
        }
        $week_list = [];

        $date = new \DateTime();//时间对象

        $date->modify('this week');//指定哪一周,默认该周的第一天

        $week_list[] = $date->format('Y-m-d');//输出周一
        for ($i = 1; $i <= 6; $i++) {
            $date->modify("this week +{$i} days");

            $week_list[] = $date->format('Y-m-d');//输出周日的年月日
        }

        $data = [];

        $redis = redis();

        $key = 'game_play_sign_' . $uid;

        foreach ($week_list as $value) {
            $temp = $redis->get($key . '_' . $value);

            if (false !== $temp) {
                $data[$value] = $temp;
            }
        }
        return $data;
    }

    /*
    @param string $op_type
    * @param $total
    * @param $uid
    */
    public static function update_user_score($op_type = '', $total, $uid, $memo = '', &$msg = '')
    {
        $after = 0;
        if ($total < 1) {
            return $after;
        }

        $info = Db::table('user')->find($uid);

        $obj_math = new Math();
        $before = $info->score;
        switch ($op_type) {
            case '+':

                $after = $obj_math->add($before, $total);

                Db::table('user')->where(['id' => $uid])->increment("score", $total);

                break;

            case '-':

                if ($before < $total) {
                    $msg = '额度不足';

                    return false;
                }

                $after = $obj_math->sub($before, $total);

                Db::table('user')->where(['id' => $uid])->decrement("score", $total);

                break;

            default:
                break;

        }

        //log
        $save = [];
        $save['user_id'] = $uid;
        $save['symbol'] = $op_type;
        $save['after'] = $after;
        $save['before'] = $before;
        $save['createtime'] = time();
        $save['score'] = $total;
        $save['memo'] = $memo;
        $save['game_id'] = 6;//麻将
        $save['type'] = getScoreLogTypeByMemo($memo);
        Db::table('user_score_log')->insert($save);

        return $after;

    }
}